<template>
  <div v-cloak>
    <div class="activityList">
      <div class="header padding20" v-if="listType === 'privilege'" >
        <div class="type-flex service">
          <div class=""><img src="@/assets/images/1-2.png" alt="background"><span class="service-text">全场包邮</span></div>
          <div class="ml-xs"><img src="@/assets/images/1-1.png" alt="background"><span class="service-text">7日无忧退货</span></div>
        </div>
        <div class="service w-full mt-xs">
          <img src="@/assets/images/1.1.png" alt="">
          <div class="type-flex service-text w-full">
            <div class="coupon-money">
              <span class="font-bold" style="font-size: .8rem">{{ Math.floor(privilegeGold.coupon_price) }}</span><span class="font-xs">元</span>
            </div>
            <div style="margin-left: 3%;">
              <div class="countdown" v-if="this.countdown">
                <span class="block" v-if="(+countdown.day) > 0">{{ countdown.day }}</span>{{ (+countdown.day) > 0 ? ' :' : '' }}
                <span class="block">{{ countdown.hour }}</span> :
                <span class="block">{{ countdown.min }}</span> :
                <span class="block">{{ countdown.sec }}</span> .
                <span class="block">{{ countdown.ms }}</span><span class="font-xs ml-xs">后作废</span>
              </div>
              <div class="font-xs mt-xs">{{ privilegeGold.ned_point ? '特权金与一起拼叠加使用 购买更超值' : '新手福利仅限首单（不可与拼团叠加）' }}</div>
            </div>
          </div>
        </div>
        <div class="tips pad20 font-xs" :class="fixedHeader ? 'is-fixed' : ''"><span class="font-bold" v-if="fixedHeader">{{ privilegeGold.coupon_price }}</span>{{ fixedHeader ? !countdown.stop ? `元特权金，  ${countdown.hour} : ${countdown.min} : ${countdown.sec} : ${countdown.ms} 后作废` : '50元新手特权金已过期' : '福利请尽快使用，可能会被好友抢走哦~' }}</div>
      </div>
      <!-- 可滑动 Tab -->
      <div class="nav" :class="fixedHeader ? 'is-fixed' : ''">
        <div class="scroll-nav" v-if="categoryList">
          <swiper ref="tabbarSwiper" :options="tabbarSwiperConfig">
              <swiper-slide v-for="(item, index) in categoryList" :key="index" style="width: auto;">
                <span @click="categoryCurrent(index, item.id, item.children)" :class="[categorySelected === index ? 'select' : '']" class="classify">{{ item.cate_name }}</span>
              </swiper-slide>
            </swiper>
        </div>
      </div>
      <!-- 选项卡对应内容 -->
      <div class="slide-page" ref="stickyBox">
        <swiper ref="pageSwiper" :options="pageSwiperConfig" @slideChangeTransitionEnd="pageSlide">
          <swiper-slide v-for="(item, index) in categoryList.length" :key="index">
            <!-- 产品列表 -->
            <div class="wrapper">
              <GoodList :isPrivilegeMoney="true" :isSort="false" :listType="listType" :categoryId="categoryId" :obj="obj" v-if="categorySelected == index"></GoodList>
            </div>
          </swiper-slide>
        </swiper>
      </div>
    </div>
  </div>
</template>
<script>
import "@assets/css/swiper.min.css";
import { swiper, swiperSlide } from "vue-awesome-swiper";
import { getCategory, getProducts } from "@api/store";
import { getUserInfo, getCouponsUser } from "@api/user";
import GoodList from "@components/GoodListIndex";
import cookie from "@utils/store/cookie";
import { isWeixin } from "@utils/index";
import { backTop, countdown } from "@utils/common.js";
import { mapGetters } from "vuex";

var vm = null;
const HAS_COUPON_WINDOW = "has_coupon_window";
export default {
  name: "ActivityList",
  components: {
    swiper,
    swiperSlide,
    GoodList,
  },
  props: {},
  data: function() {
    return {
      listType: this.$route.query.type,
      fixedHeader: false,
      status: 0,

      categoryList: [], 
      categorySelected: 0,
      categoryItem: [],
      categoryId: 0,

      //////////////////////////////////////////////////////////////////////////////// 轮播图设置开始
      tabbarSwiperConfig: {
        freeMode: true,
        freeModeMomentum: false,
        freeModeMomentumRatio: 0.5,
        slidesPerView: "auto",
        observer: true,
        observeParents: true,
        resistanceRatio:0.7,
        on: {
          click: function () {
            // 这里有坑，需要注意的是：this 指向的是 swpier 实例，而不是当前的 vue， 因此借助 vm，来调用 methods 里的方法 
            // console.log(this); // -> Swiper
            // 当前活动块的索引，与activeIndex不同的是，在loop模式下不会将 复制的块 的数量计算在内。
            const realIndex = this.realIndex;
            vm.handleClickSlide(realIndex, this);
          }
        }
      },

      pageSwiperConfig: {
        direction: 'horizontal',
        loop: false,
        autoHeight: true,
      },
      //////////////////////////////////////////////////////////////////////////////// 轮播图设置结束
      swiperWidth:'',
      maxTranslate:'',
      maxWidth:'',

      countdown: null,
      privilegeGold: null,

      obj: null,
      differenceTop: null,
    };
  },
  watch: {
    $route(n) {
      if (n.name === "ActivityList") {
        // this.getCoupon();
      }
    }
  },
  computed: mapGetters(["isLogin", "userInfo"]),
  created() {
    vm = this;

    let {type, id} = this.$route.query;
    if (type === 'privilege') {
      getCouponsUser(1).then(res => {
        this.privilegeGold = res.data.filter(item => {return item.cid === (+id)})[0];
        console.log('特权金列表筛选', this.privilegeGold);
        let endTime = Number(this.privilegeGold.end_time + '000'), ms = 10;
        let timer = setInterval(() => {
          ms--;    
          if (ms === -1) {
            ms = 9;
          }
          this.countdown = countdown(endTime, ms);
          if (this.countdown.stop) {
            clearInterval(timer);
          }
        }, 100);
      }).catch(err => {
        this.$dialog.error(err.msg);
      });
    }
  },
  mounted: function() {
    this.getCategoryData();
    this.obj = this.$el;
    this.$nextTick(() => {
      this.differenceTop = this.$refs.stickyBox.offsetTop;
    });
    window.addEventListener("scroll",this.handleScroll); 
  },
  destroyed() {
    document.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 滚动条监听
    handleScroll() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.fixedHeader = scrollTop > (this.differenceTop + 50) ? true : false;
    },

    // tabbar点击事件
    handleClickSlide(index, swiper) { 
        let that = this;
        if (that.$refs.pageSwiper.swiper.realIndex !== that.categorySelected) {
          that.$refs.pageSwiper.swiper.slideTo(that.categorySelected, 350, false);
        }
        backTop();
        that.swiperWidth = that.$refs.tabbarSwiper.swiper.slides['1'].clientWidth;
        that.maxTranslate = that.$refs.tabbarSwiper.swiper.maxTranslate(); // 最大可移动距离（负值）
        that.maxWidth = that.maxTranslate / 2;
        that.loading_show=true;
        var boxCenter=(that.$refs.tabbarSwiper.swiper.el.clientWidth)/2,  scrollLeft = (that.categorySelected)*that.swiperWidth/2;
        that.$refs.tabbarSwiper.swiper.setTransition(200);
        if (-scrollLeft > -boxCenter+that.swiperWidth) {  //当前tab所在位置大于盒子居中位置时，回scroll盒子的首位
          that.$refs.tabbarSwiper.swiper.setTranslate(0);
          return;
        }
        if (-scrollLeft-that.swiperWidth < (that.maxTranslate+boxCenter+(that.swiperWidth/2))) {
          that.$refs.tabbarSwiper.swiper.setTranslate(that.maxTranslate);
          return;
        }
        that.$refs.tabbarSwiper.swiper.setTranslate(-scrollLeft-(that.categorySelected-3)*(that.swiperWidth/2));
    },
    categoryCurrent(index, id, item) {
      this.categorySelected = index;
      this.categoryId = id;
      setTimeout( () => {
        this.categoryItem = item; 
      }, this.$refs.pageSwiper.swiper.realIndex !== this.categorySelected ? 400 : 0);
    },

    // 页面滑动事件
    pageSlide() {
      let index = this.$refs.pageSwiper.swiper.realIndex;
      this.categoryCurrent(index, this.categoryList[index].id, this.categoryList[index].children);
      this.handleClickSlide();
    },

    // 获取分类
    getCategoryData: function() {
      let that = this;
      getCategory().then(res => {
        console.log('获取分类', res);
        for (let i in res.data) {
          if (res.data[i].children.length) {
            this.categoryList.push(res.data[i]);
          }
        }
        this.categoryList.unshift({
          cate_name: '精选热门'
        });
      });
    },
  }
}
</script>

<style scoped>
/deep/ .slide-page .swiper-wrapper {
  height: auto!important;
}

img {
  display: block;
  width: 100%;
}

.activityList .header .service, .activityList .header .service>div{
  position: relative;
}
.activityList .header .service.w-full::after {
  content: "";
  display: inline-block;
  position: absolute;
  bottom: 0;
  z-index:9;
  width: 100%;
  height: 7px;
  background-image: -webkit-radial-gradient(circle, transparent, transparent 5px, #ffeec9 5px,#ffeec9);
  background-image: -moz-radial-gradient(circle, transparent, transparent 5px, #ffeec9 5px, #ffeec9);
  background-image: radial-gradient(circle, transparent, transparent 5px, #ffeec9 5px, #ffeec9);
  background-size: 12px 20px;
  transform: rotate(180deg);
  -webkit-transform: rotate(180deg);
}
.activityList .header .service .service-text {
  padding-left: 4%;
  padding-right: 4%;
  color: #ffe8d4;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2;
}
.activityList .header .coupon-money {
  padding-right: 4%;
  border-right: 1px solid brown;
  border-right-style: dashed;
}
.activityList .header .service .service-text .countdown .block {
  background-color: brown;
  padding: .02rem .08rem;
  border-radius: .03rem;
}
.activityList .header .tips {
  height: .5rem;
  line-height: .5rem;
  color: #bb904d;
  background-color: rgb(255, 238, 201);
  border-radius: 0 0 .1rem .1rem;
}
.activityList .header .tips.is-fixed {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 9;
  text-align: center;
  border-radius: 0;
  margin-left: -.2rem;
}

/* 顶部选项卡 */
.nav {
  width: 100%; height: .8rem; padding: 0 0.3rem; background-color: #fff; border-bottom: 1px solid #eee;
}
.nav.is-fixed {
  position: fixed; top: .5rem; z-index: 9;
}
.scroll-nav { 
  padding-top: .1rem; color: #555; position: relative; z-index: 2; overflow: hidden;
}
.scroll-nav .classify {
  display: inline-block; padding: .15rem .15rem .1rem; margin-right: .2rem;
}
.scroll-nav .classify.select {
  color: #7f4395; border-bottom: .03rem solid #7f4395; font-weight: bold;
}

.slide-page.is-fixed {
  margin-top: 1.3rem;
}
</style>